package org.dxw.common.excel;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder;
import lombok.Data;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author dxw
 * @Date 2023/1/2 14:51
 * @Description
 */
@Data
public class MySheetWriteHandler implements SheetWriteHandler {

    //sheet 对应的单元格合并对象
    private Map<String, List<CellRangeAddress>> sheetCellRange = new HashMap<>();

    @Override
    public void beforeSheetCreate(SheetWriteHandlerContext context) {
        SheetWriteHandler.super.beforeSheetCreate(context);
    }

    @Override
    public void beforeSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        SheetWriteHandler.super.beforeSheetCreate(writeWorkbookHolder, writeSheetHolder);
    }

    @Override
    public void afterSheetCreate(SheetWriteHandlerContext context) {
        SheetWriteHandler.super.afterSheetCreate(context);
    }

    @Override
    public void afterSheetCreate(WriteWorkbookHolder writeWorkbookHolder, WriteSheetHolder writeSheetHolder) {
        merge(writeSheetHolder);
    }

    private void merge(WriteSheetHolder writeSheetHolder){
        Sheet sheet = writeSheetHolder.getSheet();
        List<CellRangeAddress> cellRangeAddresses = sheetCellRange.get(sheet.getSheetName());
        if(CollUtil.isNotEmpty(cellRangeAddresses)){
            for (CellRangeAddress cellRangeAddress : cellRangeAddresses) {
                sheet.addMergedRegionUnsafe(cellRangeAddress);
            }
        }
    }


}
